//
//  JCIdentityVerificationViewController.swift
//  JChat
//
//  Created by JIGUANG on 2017/4/5.
//  Copyright © 2017年 HXHG. All rights reserved.
//

import UIKit

import MTCategory
import Result
import RxSwift
import RxCocoa

class JCIdentityVerificationViewController: BaseViewController {

    fileprivate var badgeCount = 0
    let provider: MTProvider = MTProvider<MTClubApi>()
    let userProvider: MTProvider = MTProvider<UserCenterApi>()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.theme.background
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints {
            $0.edges.equalToSuperview()
        }
        _init()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        UserDefaults.standard.set(0, forKey: kUnreadInvitationCount)
        if UserDefaults.standard.object(forKey: kUnreadInvitationCount) != nil {
            badgeCount = UserDefaults.standard.object(forKey: kUnreadInvitationCount) as! Int
        } else {
            badgeCount = 0
        }
        if badgeCount > 99 {
            navigationVC?.tabBarItem.badgeValue = "99+"
        } else {
            navigationVC?.tabBarItem.badgeValue = badgeCount == 0 ? nil : "\(badgeCount)"
        }

    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    private var infos: [JCVerificationInfo] = []
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain).then {
            $0.register(JCVerificationCell.self, forCellReuseIdentifier: JCVerificationCell.reuseIdentity())
            $0.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: CGFloat.leastNormalMagnitude))
            $0.backgroundColor = UIColor.theme.background
        }
        if #available(iOS 11.0, *) {
//            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            //self.automaticallyAdjustsScrollViewInsets = false
            //tableView.translatesAutoresizingMaskIntoConstraints = false
        }
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 70;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.emptySetView = ViewFactory.emptySetView()
        return tableView
    }()
    
    // MARK: - private func
    private func _init() {
        self.title = "待处理请求"
        _getData()
        NotificationCenter.default.addObserver(self, selector: #selector(_getData), name: NSNotification.Name(rawValue: kUpdateVerification), object: nil)
    }
    
    @objc func _getData() {
        infos.removeAll()
        infos = JCVerificationInfoDB.shareInstance.quaryData(verType: 1)
        tableView.reloadData()
    }
}

extension JCIdentityVerificationViewController: JCVerificationCellDelegate {
    
    /// 同意申请信息
    /// - Parameters:
    ///   - userName: 同意的用户信息
    ///   - eventType: 事件类型1同意加好友，2同意加俱乐部
    ///   - pushId: 群组ID
    func acceptInvitation(userName: String, eventType: Int, pushId: String?) {
        let requestParam: [String : Any] = ["eventType": eventType, "pushId": pushId ?? "", "userName": userName]
        
        UserCenterApiTool.notify(provider: userProvider, requestParam: requestParam, complete: { (model) in
            
        }) { (error) in
            
        }
    }
    
}

extension JCIdentityVerificationViewController: MTVerficateDetailViewControllerDelegate {
    func confrimInvitation(userName: String) {
        self.tableView.reloadData()
    }
    
    func rejectInvitation() {
        self.tableView.reloadData()
    }
}


extension JCIdentityVerificationViewController: UITableViewDelegate, UITableViewDataSource {
    // MARK: - Table view data source
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return infos.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: JCVerificationCell = tableView.dequeueReusableCell(withIdentifier: JCVerificationCell.reuseIdentity(), for: indexPath) as! JCVerificationCell
        cell.delegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        guard let cell = cell as? JCVerificationCell else {
            return
        }
        cell.bindData(infos[indexPath.row])
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let info = infos[indexPath.row]
        
        if info.type == .single { // 好友申请
            /// 好友申请发起者, 不是自己
            if info.initiator != JMSGUser.myInfo().username {
                let vc = MTVerficateDetailViewController()
                vc.info = info
                vc.delegate = self
                self.navigationController?.pushViewController(vc, animated: true)
            } else {
                let c = MineViewController(username: info.username)
                self.navigationController?.pushViewController(c, animated: true)
            }
        } else if info.type == .group { // 群组申请
            let c = MineViewController(username: info.initiator)
            self.navigationController?.pushViewController(c, animated: true)
        }
        
//        let c = MineViewController(username: info.type == 1 ? info.username : info.initiator)
//        self.navigationController?.pushViewController(c, animated: true)
        
//        switch info.state {
//        case JCVerificationType.accept.rawValue,
//             JCVerificationType.reject.rawValue,
//             JCVerificationType.wait.rawValue:
////            JMSGUser.userInfoArray(withUsernameArray: [info.username], completionHandler: { (result, error) in
////                if error == nil {
////                    let users = result as! [JMSGUser]
////                    let user = users.first
////                    let vc = JCUserInfoViewController()
////                    vc.user = user
////                    self.navigationController?.pushViewController(vc, animated: true)
////                }
////            })
//            let c = MineViewController(username: info.username)
//            self.navigationController?.pushViewController(c, animated: true)
//        case JCVerificationType.receive.rawValue:
////            let vc = JCVerificationDetailViewController()
////            vc.verificationInfo = info
////            navigationController?.pushViewController(vc, animated: true)
//            let c = MineViewController(username: info.username)
//            self.navigationController?.pushViewController(c, animated: true)
//        default:
//            break
//        }
    }
    
//    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
//        return true
//    }
//
//    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
//        return .delete
//    }
//
//    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
//        if editingStyle == .delete {
//            let info = infos[indexPath.row]
//            JCVerificationInfoDB.shareInstance.delete(info)
//            infos.remove(at: indexPath.row)
//            tableView.reloadData()
//        }
//    }
}

extension JCIdentityVerificationViewController {
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
        return false
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let deleteAction:UIContextualAction = UIContextualAction(style: .destructive, title: "") { (action, sourceView, completionHandler) in
            completionHandler(true)
            self.deleteFriend(indexPath)
        }
        deleteAction.image = UIImage(named: "icon_trash")
        deleteAction.backgroundColor = UIColor(hex: 0xFFC000)
        let actions:[UIContextualAction] = [deleteAction]
        let action:UISwipeActionsConfiguration = UISwipeActionsConfiguration(actions: actions)
        action.performsFirstActionWithFullSwipe = false
        return action
    }
    
    private func deleteFriend(_ indexPath: IndexPath) {
        let info = infos[indexPath.row]
        /// 如果是已经通过申请 / 拒绝申请 / 位置状态的验证信息可以直接删除
        if [JCVerificationType.reject.rawValue,
            JCVerificationType.accept.rawValue,
            JCVerificationType.unkonw.rawValue].contains(info.state) {
            JCVerificationInfoDB.shareInstance.delete(info)
            self.infos.remove(at: indexPath.row)
            DispatchQueue.main.async {
                self.tableView.deleteRow(at: indexPath, with: .none)
//                self.tableView.reloadData()
            }
            return
        }
        
        let infoTips = info.type == .single ? "确认要删除好友申请？" : "确认要删除俱乐部申请？"
        UIAlertController.rx.show(in: self, title: nil, message: infoTips, buttons: [.cancel("取消"), .default("确认")]).subscribe(onSuccess: { [weak self] index in
            guard let weakSelf = self else { return }
            if index == 1 {
                if info.type == .single {
                    JCVerificationInfoDB.shareInstance.delete(info)
                    weakSelf.infos.remove(at: indexPath.row)
                    DispatchQueue.main.async {
                        //weakSelf.tableView.reloadData()
                        weakSelf.tableView.deleteRow(at: indexPath, with: .none)
                    }
                } else {
                    
                    JMSGUser.userInfoArray(withUsernameArray: [info.initiator]) { [weak self] (result, error) in
                        guard let weakSelf = self else { return }
                        if error == nil, let users = result as? [JMSGUser], users.count > 0, let u = users.first {
                            JMSGGroup.processApplyJoinEventID(info.eventId, gid: info.username, join: u, apply: u, isAgree: false, reason: nil) { (result, error) in
                                if error == nil {
                                    //info.state = JCVerificationType.reject.rawValue
                                    //JCVerificationInfoDB.shareInstance.updateData(info)
                                    JCVerificationInfoDB.shareInstance.delete(info)
                                    weakSelf.infos.remove(at: indexPath.row)
                                    DispatchQueue.main.async {
                                        //weakSelf.tableView.reloadData()
                                        weakSelf.tableView.deleteRow(at: indexPath, with: .none)
                                    }
                                } else {
                                    if let e: NSError = error as? NSError, e.code == 856002 {
                                        JCVerificationInfoDB.shareInstance.delete(info)
                                        weakSelf.infos.remove(at: indexPath.row)
                                        DispatchQueue.main.async {
                                            //weakSelf.tableView.reloadData()
                                            weakSelf.tableView.deleteRow(at: indexPath, with: .none)
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }).disposed(by: globalDisposedBag)
    }
    
}

